﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PesticideManage.API.Data;
using PesticideManage.API.Extensions;
using PesticideManage.API.Models;
using PesticideManage.API.Services.Identity.Dtos;
using PesticideManage.API.Services.Identity.UserAggregate;
using PesticideManage.API.Services.JWT;
using Shang.Sms;
using System.Reflection;

namespace PesticideManage.API.Controllers;
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    private readonly IAuthTokenService _authTokenService;
    private readonly PesticideContext _context;
    private readonly ISmsService _smsService;

    public UserController(IAuthTokenService authTokenService, PesticideContext context, ISmsService smsService)
    {
        _authTokenService = authTokenService;
        _context = context;
        _smsService = smsService;
    }
    /// <summary>
    /// 获取用户
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public async Task<ActionResult<User>> Get()
    {
        int userId = User.GetId();
        var user = await _context.Users
            .AsNoTracking()
            .Include(u => u.Roles)
            .FirstOrDefaultAsync(u => u.Id == userId);
        if (user is null)
        {
            return NotFound($"用户{User.Identity?.Name}不存在");
        }
        return Ok(user);
    }
    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="user"></param>
    /// <returns></returns>
    [HttpPut]
    public async Task<IActionResult> PutAsync(User user)
    {
        _context.Entry(user).State = EntityState.Modified;
        try
        {
            await _context.SaveChangesAsync();
        }
        catch (Exception)
        {

            throw;
        }
        return NoContent();
    }
    public struct ChangePasswordDTO
    {
        public required string Password { get; set; }
        public required string NewPassword { get; set; }
    }
    /// <summary>
    /// 修改密码
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPatch("ChangePassword")]
    public async Task<IActionResult> Patch(ChangePasswordDTO dto)
    {
        int userId = User.GetId();
        var user = await _context.Users.Where(u => u.Id == userId).Select(u => new User(u.Id, u.Password)).FirstOrDefaultAsync();
        if (user is null || !user.VerifyPassword(dto.Password))
        {
            return BadRequest("密码错误");
        }
        user.SetPassword(dto.NewPassword);
        //var user = new User { Name = "", Id = userId, };
        //user.SetPassword(dto.Password);
        //_context.Attach(user);
        _context.Entry(user).Property(u => u.Password).IsModified = true;
        //var user = await _context.Users.FirstAsync(u => u.Id == userId);
        //if (user is null)
        //{
        //    return NotFound("用户不存在");
        //}
        //user.Password = Password;
        //user.SetPassword(Password);
        await _context.SaveChangesAsync();
        return NoContent();
    }
    [HttpPatch]
    public async Task<IActionResult> Patch(UserModifiablePart userModifiablePart)
    {
        int userId = User.GetId();
        var user = await _context.Users.FindAsync(userId);
        if (user is null)
        {
            return NotFound($"用户{User.Identity?.Name}不存在");
        }
        user.MobileNumber = userModifiablePart.MobileNumber ?? user.MobileNumber;
        user.Email = userModifiablePart.Email ?? user.Email;
        user.Address = userModifiablePart.Address ?? user.Address;
        _context.SaveChanges();
        return NoContent();
    }
    [HttpPost("[action]")]
    public async Task<IActionResult> VerifyPasswordAsync(string password)
    {
        var userId = User.GetId();
        var user = await _context.Users.Where(u => u.Id == userId).Select(u => new User(u.Id, u.Password)).FirstAsync();
        if (user is null || !user.VerifyPassword(password))
        {
            return BadRequest("密码错误");
        }
        return NoContent();
    }

    [HttpPatch("[action]")]
    public async Task<IActionResult> UpdateMobile(UpdateMobileDTO updateMobileDTO)
    {
        var userId = User.GetId();
        var user = await _context.Users.Where(u => u.Id == userId).Select(u => new User(u.Id, u.Password)).FirstAsync();
        if (user is null || !user.VerifyPassword(updateMobileDTO.Password))
        {
            return BadRequest("密码错误");
        }
        if (!_smsService.VerifyCode(updateMobileDTO.MobileNumber, updateMobileDTO.Smsvcode))
        {
            return BadRequest("验证码错误");
        }
        user.MobileNumber = updateMobileDTO.MobileNumber;
        _context.Entry(user).Property(u => u.MobileNumber).IsModified = true;
        await _context.SaveChangesAsync();
        return NoContent();
    }

    /// <summary>
    /// 实名认证
    /// </summary>
    /// <param name="authenticationDTO"></param>
    /// <returns></returns>
    [HttpPut("[action]")]
    public async Task<NoContentResult> Authentication(AuthenticationDTO authenticationDTO)
    {
        int userId = User.GetId();
        var user = await _context.Users.FindAsync(userId);
        ArgumentNullException.ThrowIfNull(user);
        user.IDCard = authenticationDTO.ID;
        user.Enterprise = authenticationDTO.Enterprise;
        await _context.SaveChangesAsync();
        return NoContent();
    }
    /// <summary>
    /// 更新地址
    /// </summary>
    /// <param name="address"></param>
    /// <returns></returns>
    [HttpPut("[action]")]
    public async Task<ActionResult<User>> Address(Address address)
    {
        var user = await GetUserAsync();
        user.Address = address;
        await _context.SaveChangesAsync();
        return Ok(user);
    }
    private async Task<User> GetUserAsync()
    {
        int userId = User.GetId();
        var user = await _context.Users.FindAsync(userId);
        ArgumentNullException.ThrowIfNull(user);
        return user;
    }
}
